package com.marver.common.handler;

import com.marver.common.enumeration.LabeledEnumResolver;
import com.marver.common.enumeration.StringLabeledEnum;
import com.marver.common.utils.SpringUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * mybatis 数据字典自动转换实现
 * @author kaede
 *
 */
@MappedTypes(value=StringLabeledEnum.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class StringLabeledEnumTypeHandler extends BaseTypeHandler<StringLabeledEnum> {
	
	@Override
	public void setNonNullParameter(PreparedStatement ps, int i,
			StringLabeledEnum parameter, JdbcType jdbcType) throws SQLException {
		// TODO Auto-generated method stub
		//设置给ps
        ps.setString(i, parameter.getCode());
	}

	@Override
	public StringLabeledEnum getNullableResult(ResultSet rs, String columnName)
			throws SQLException {
		// TODO Auto-generated method stub
		LabeledEnumResolver labeledEnumResolver=SpringUtil.getBean("labeledEnumResolver",LabeledEnumResolver.class);
		String msgcode=rs.getString(columnName);
		return labeledEnumResolver.getStringLabeledEnum(msgcode);
	}

	@Override
	public StringLabeledEnum getNullableResult(ResultSet rs, int columnIndex)
			throws SQLException {
		LabeledEnumResolver labeledEnumResolver=SpringUtil.getBean("labeledEnumResolver",LabeledEnumResolver.class);
		String msgcode=rs.getString(columnIndex);
		return labeledEnumResolver.getStringLabeledEnum(msgcode);
	}

	@Override
	public StringLabeledEnum getNullableResult(CallableStatement cs,
			int columnIndex) throws SQLException {
		LabeledEnumResolver labeledEnumResolver=SpringUtil.getBean("labeledEnumResolver",LabeledEnumResolver.class);
		String msgcode=cs.getString(columnIndex);
		return labeledEnumResolver.getStringLabeledEnum(msgcode);
	}
	
}